package com.xscha.soyue.common.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.env.Environment;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * SpringContextHolder
 *
 * @author Vondser
 * @version V2024.1.0
 */
@Component
@SuppressWarnings("unchecked")
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

	private static ApplicationContext applicationContext = null;

	public static <T> T getBean(String name) {
		return (T) Objects.requireNonNull(applicationContext).getBean(name);
	}

	public static <T> T getBean(Class<T> clazz) {
		return Objects.requireNonNull(applicationContext).getBean(clazz);
	}

	public static <T> T getProperties(String key) {
		return (T) getProperties(key, null, String.class);
	}

	public static <T> T getProperties(String key, Class<T> requiredType) {
		return getBean(Environment.class).getProperty(key, requiredType);
	}

	public static <T> T getProperties(String key, T defaultValue, Class<T> requiredType) {
		try {
			defaultValue = getBean(Environment.class).getProperty(key, requiredType);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return defaultValue;
	}

	public ApplicationContext getApplicationContext() {
		return Objects.requireNonNull(applicationContext);
	}

	@Override
	public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
		Assert.notNull(applicationContext, "application context cannot be null");
		SpringContextHolder.applicationContext = applicationContext;
	}

	/**
	 * 发布事件
	 * @param event
	 */
	public static void publishEvent(ApplicationEvent event) {
		if (applicationContext == null) {
			return;
		}
		applicationContext.publishEvent(event);
	}

	@Override
	public void destroy() {
		applicationContext = null;
	}

}
